import React, {PureComponent} from "react"
import {bindActionCreators} from "redux"
import {connect} from "react-redux"
import cs from  "classnames";
import { cloneDeep,find} from "lodash";
import PropTypes from "prop-types";
import adminImg from "../../../images/admin.png";
import persionImg from "../../../images/person.png";
/*ant 组件*/
import {Timeline,Input,Button,Icon,Select,Checkbox} from "antd"
import {filterName} from "../../../libs/util/index"
import {renameOrganize,addAdmin,removeManager,delPerson} from "../actions";
import OrganizeAddPerson from "./organizeSettingAddPerson";//添加人员
import OrganizeEditPerson from "./organizeSettingEditPerson";//编辑人员
import OrganizeAddAdmin from "./organizeSettingAddAdmin";//新增管理员页面
import OrganizeAddOtherPerson from "./organizeSettingAddOtherPerson";//导入无部门人员
/*css依赖*/
import "./organize.less"
const propTypes = {
    close: PropTypes.func.isRequired,
    info: PropTypes.object.isRequired,
};
/*redux连接池*/
@connect(
    ({duty,base}) => ({
        duty:duty.duty
    }),
    (dispatch) => (
        bindActionCreators({
            renameOrganize,
            addAdmin,
            removeManager,
            delPerson,
        }, dispatch)
    )
)
export default class Index extends PureComponent {
    state = {
        rename:true,
        editPerson:false,//切换编辑状态
        editPersonId:[],//已经选中的id
        personType:"-1",
        addPersonModal:false,//是否显示新增人员
        editPersonModal:false,//是否显示编辑人员页面
        addAdminModal:false,//是否显示新增管理员页面
        addOtherModal:false,//是否显示导入无部门人员
    }
    render() {
        const {info,close,admin,person} = this.props;
        console.info("人员信息",admin,person);
        const {rename,editPerson,editPersonId,addPersonModal,editPersonModal,addAdminModal,addOtherModal} = this.state;
        return (
            <div className="organize-setting">
                <div className="organize-setting-content">
                    <h4>
                        <span onClick={close}><Icon type="right" />收起</span>
                        <span><Icon type="delete" />删除部门</span>
                    </h4>
                    <div className="organize-setting-title">
                        <span onClick={this.doRename} className={cs("organize-setting-title-name",!rename?"hide":"show")}>
                                    {info.name}<Icon type="edit" />
                        </span>
                        <div className={cs("organize-setting-title-input",rename?"hide":"show")}>
                            <Input
                                ref="input"
                                defaultValue={info.name}
                                placeholder="请输入单位名称"
                                onBlur={this.changeName}
                            />
                        </div>
                        <span className="organize-setting-title-action">进入部门<Icon type="right" /></span>
                    </div>
                    <div className="organize-setting-manager">
                        <ul>
                            <li>
                                <img src={adminImg} alt=""/>
                                <h5>管理员</h5>
                                <p>{admin.length+1}人</p>
                                <Button onClick={()=>{this.setState({addAdminModal:true})}}>添加</Button>
                            </li>
                            <li onDragOver={this.allowDrop} onDrop={this.drop}>
                                <p>成为管理员可以增加删改本部门中的人员</p>
                                {
                                    this.admins()
                                }
                            </li>
                        </ul>
                    </div>
                    <div className="organize-setting-people">
                        <ul>
                            <li>
                                <img src={persionImg} alt=""/>
                                <h5>人员</h5>
                                <p>{person.length}人</p>
                                {
                                    !!person.length && <Button onClick={this.doEdit} className="add-all">{editPerson&&"完成"||"批量管理"}</Button>
                                }
                                <Button onClick={()=>{this.setState({addPersonModal:true})}}>添加</Button>
                            </li>
                            <li>
                                <div className="organize-setting-people-action">
                                    {
                                        this.getDuty()
                                    }
                                    {
                                        editPerson && <div className="editing">
                                            <Checkbox checked={this.checkStatus()}  onChange={this.checkAll}>全选</Checkbox>
                                            {
                                                !!editPersonId.length && <span>已选择{editPersonId.length}人</span>
                                            }
                                            <span className="del" onClick={this.doDelPerson}>删除</span>
                                            <span className="edit" onClick={()=>{
                                                if(!!editPersonId.length){
                                                    this.setState({
                                                        editPersonModal:true
                                                    })
                                                }
                                            }}>编辑</span>
                                        </div>
                                    }
                                    {
                                        !editPerson && <span>将头像拖拽到上方 ↑ 管理员区域，即可设置为管理员</span>
                                    }
                                </div>
                                {
                                    this.people()
                                }
                            </li>
                        </ul>
                    </div>
                </div>
                {
                    addPersonModal && <OrganizeAddPerson
                        close={()=>{this.setState({addPersonModal:!addPersonModal})}}
                        info={info}
                        person={person}
                        showNoAssess={()=>{this.setState({
                            addOtherModal:true
                        })}}
                    />
                }
                {
                    editPersonModal && <OrganizeEditPerson
                        close={()=>{this.setState({
                            editPersonModal:!editPersonModal,
                            editPersonId:[],
                            editPerson:false
                        })}}
                        info={info}
                        person={this.getEditPerson()}
                    />
                }
                {
                    addAdminModal && <OrganizeAddAdmin
                        close={()=>{this.setState({
                            addAdminModal:!addAdminModal
                        })}}
                        info={info}
                        restPerson={this.getRestPerson()}
                        admin={admin}
                    />
                }
                {
                    addOtherModal && <OrganizeAddOtherPerson
                        close={()=>{this.setState({
                            addOtherModal:!addOtherModal
                        })}}
                        info={info}
                    />
                }

            </div>
        )
    }
    componentDidMount() {
    }

    /**
     * 获取无部门人员
     */
    getNoAssessPerson=()=>{
        let {person} = this.props;
        return person.filter((i)=>{
            return i.assess == "";
        })
    };
    /**
     * 获取除开admin 余下的全部人员
     */
    getRestPerson=()=>{
        let {admin,person} = this.props;
        return person.filter((i)=>{
            return (!find(admin,z=>z.id === i.id) && i.manager!="-1")
        })
    };
    /**
     * 获取编辑状态中选定的人
     */
    getEditPerson=()=>{
        let {editPersonId} = this.state;
        let {person} = this.props;
        return person.filter(i=>{
            return editPersonId.indexOf(i.id)>-1;
        })
    }
    /**
     * 检测全选按钮状态
     */
    checkStatus=()=>{
        let {editPersonId,personType} = this.state;
        let {person,admin,info} = this.props;
        let items = [];
        if("-1" === personType){
            items = person;
        }else{
            items =  person.filter(i=>{return i.job == personType});
        }
        for(let x in items){
            if(-1 === editPersonId.indexOf(items[x].id)){
                return false;
            }
        }
        return true;
    };
    /**
     * 删除人员同时清空正在编辑中人员
     */
    doDelPerson=()=>{
        let {editPersonId} = this.state;
        let {delPerson} = this.props;
        delPerson({
            ids:editPersonId
        })
        this.setState({
            editPersonId:[],
        })
    }
    /**
     * 切换编辑状态
     */
    doEdit=()=>{
        let {editPerson,editPersonId} = this.state;
        this.setState({
            editPerson:!editPerson,
            editPersonId:!editPerson?[]:editPersonId
        })
    }
    /**
     * 生成职务筛选
     * @returns {XML}
     */
    getDuty =()=>{
        let {duty} = this.props;
        let {personType} = this.state;
        let newDuty = cloneDeep(duty);
        newDuty.unshift({
            id:-1,
            name:"不限职务"
        });
        return (
            <Select placeholder="请选择条件判断!" value={personType+""} onChange={this.changePersonType}>
                {
                    newDuty.map((i,index)=>{
                        return <Select.Option key={i.name}  value={i.id+""}>{i.name}</Select.Option>
                    })
                }
            </Select>
        )
    }
    /**
     * 修改当前选择职务，并清空被编辑人员数组
     * @param personType
     */
    changePersonType=(personType)=>{
        this.setState({
            personType,
            editPersonId:[],
        })
    }
    /**
     * 生成admin列表
     * @returns {XML}
     */
    admins=()=>{
        let {person,admin,info,removeManager} = this.props;
        return <div className="organize-setting-names">
            <div>
                <div>admin</div>
                <p>admin</p>
            </div>
            {
                admin.map((i,index)=>{
                    return <div key={i.name}>
                        <div>{filterName(i.realName,2)}
                            <span className="admin" onClick={()=>{removeManager({id:i.id})}}>-</span>
                        </div>
                        <p>{i.realName}</p>
                    </div>
                })
            }
        </div>
    }
    /**
     * 全选状态切换
     * @param e
     */
    checkAll=(e)=>{
        let status = e.target.checked;
        let {personType} = this.state;
        let {person,admin,info} = this.props;
        let items = [];
        let editPersonId = [];
        if("-1" === personType){
            items = person;
        }else{
            items =  person.filter(i=>{return i.job == personType});
        }
        if(status){
            for(let x in items){
                editPersonId.push(items[x].id);
            }
        }
        this.setState({
            editPersonId
        })
    }
    /**
     * 根据职务过滤 人员
     * @returns {XML}
     */
    people=()=>{
        let {editPerson,editPersonId,personType} = this.state;
        let {person,admin,info} = this.props;
        let items = [];
        if("-1" === personType){
            items = person;
        }else{
            items =  person.filter(i=>{return i.duty == personType});
        }
        return <div className="organize-setting-names">
            {
                items.map((i,index)=>{
                    return <div key={i.realName} draggable="true" onDragStart={(e)=>{this.drag(e,i)}} onClick={()=>{this.addEdit(i)}}>
                        <div>{filterName(i.realName,2)}
                            {
                                (editPerson && editPersonId.indexOf(i.id)>-1) && <span className="person"><Icon type="check" /></span>
                            }
                        </div>
                        <p>{i.realName}</p>
                    </div>
                })
            }
        </div>
    }
    /**
     * 被编辑人员入栈出栈
     * @param item
     * @returns {boolean}
     */
    addEdit=(item)=>{
        let {editPersonId,editPerson} = this.state;
        let ids = cloneDeep(editPersonId);
        if(!editPerson)
            return false;
        if(ids.indexOf(item.id) === -1){
            ids.push(item.id);
            this.setState({
                editPersonId:ids
            })
        }else{
            let newIds = ids.filter(i=>{
                return i !== item.id;
            })
            this.setState({
                editPersonId:newIds
            })
        }

    }
    /**
     * 重命名
     * @param e
     */
    changeName=(e)=>{
        let { info,renameOrganize } = this.props;
        let value = e.target.value;
        this.doRename();
        renameOrganize(Object.assign(info,{name:value}));
    };
    /**
     * 切换名称显示状态
     */
    doRename=()=>{
        let { rename } = this.state;
        let {input} = this.refs;
        this.setState({
            rename:!rename
        },()=>{
            if(rename){
                input.focus()
            }
        })
    }
    drag=(e,data)=>{
        e.dataTransfer.setData("Text",JSON.stringify(data))
    };
    allowDrop=(e)=>{
        e.preventDefault();
    };
    drop=(ev)=>{
        let {admin,info,addAdmin} = this.props;
        let {editPerson} = this.state;
        ev.preventDefault();
        let data=ev.dataTransfer.getData("Text");
        data = JSON.parse(data);
        let current = find(admin,i=>{
            return i.id == data.id;
        });
        if(current || editPerson){//在编辑状态,已结存在了，不能拖动
            return false;
        }else {
            addAdmin({
                staffId:info.id,
                info:data
            })
        }
    };
}
